<?php
/*
PekeUpload
Copyright (c) 2013 Pedro Molina
*/

function getFileExtension($filePath) {
	$path_parts = pathinfo($filePath);
	if (!isset($path_parts['extension']))
		return null;
	return '.' . $path_parts['extension'];
}

// Define a destination
$targetFolder = 'resources/background/' . $_POST['data'];
if (!file_exists($targetFolder))
  mkdir($targetFolder, 0777, true);

if (!empty($_FILES)) {
	$tempFile = $_FILES['file']['tmp_name'];
	$systemFileName = md5($_FILES['file']['name'] . rand() . microtime()) . getFileExtension($_FILES['file']['name']);
	$targetPath = dirname(__FILE__) . '/' . $targetFolder;
	$targetFile = rtrim($targetPath,'/') . '/' . $systemFileName;
	
	// Validate the file type
	$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
	$fileParts = pathinfo($_FILES['file']['name']);
	
	if (in_array($fileParts['extension'], $fileTypes)) {
		move_uploaded_file($tempFile,$targetFile);
		echo json_encode(array('code' => 1, 'targetFile' => $targetFile, 'path' => $_POST['data'] . $systemFileName));
	} else {
		echo json_encode(array('code' => 0, 'message' => 'Dozwolone pliki to: *.' . implode(', *.', $fileTypes)));
	}
}
?>